<template>
  <div class="JD-channel">
    <header v-if="!isDisabled || isEditorDescription">
      <el-button size="mini" type="primary" round @click="saveSpuChannelInfo">保 存</el-button>
    </header>
    <div class="channel-content">
      <div class="content-left">
        <el-button
          v-for="(item, index) in headerList"
          :key="index"
          v-anchor="{ id: item.id, el: '.content-right' }"
          :class="current == index ? 'el-button-text btn-active' : 'el-button-text'"
          type="text"
        >
          <strong>{{ item.label }}</strong>
        </el-button>
      </div>

      <div ref="contentRight" class="content-right" @scroll.self="scrollFunc">
        <div id="anchor-1">
          <info-item ref="info-item" :form-data="spuData" :is-disabled="isDisabled" :channel-info="channelInfo" :increased="increased" />
          <channelAttr ref="channelAttr" :commodity-attribute="channelInfo" :gutter="40" :is-disabled="isDisabled" :increased="increased" />
        </div>

        <productPicture
          id="anchor-2"
          ref="productPicture"
          :increased="increased"
          :is-disabled="photoDisable"
          :channel-info="channelInfo"
          :main-sale-attr-value-list="channelInfo.spuSaleAttr.mainSaleAttr.mainSaleAttrValueList"
          :main-sale-attr-name="channelInfo.spuSaleAttr.mainSaleAttr.mainSaleAttrName"
        />

        <textDescription
          id="anchor-3"
          ref="textDescription"
          :increased="increased"
          :is-disabled="photoDisable"
          :spu-channel-desc="channelInfo.spuChannelDesc"
        />

        <seriesList id="anchor-4" :increased="increased" :list="spuData.skuInfoList" :thead-list="theadList" @handleSinkingAttribute="handleSinkingAttribute" />

        <sinking-attribute
          v-model="dialogVisible"
          :is-disabled="isDisabled"
          :loading="loading"
          :commodity-attribute="sinkingAttributeInfo.spuChannelCategoryAttrList"
          @submitSinkingAttribute="submitSinkingAttribute"
        />
      </div>
    </div>
  </div>
</template>

<script>
import infoItem from './infoItem.vue'
import productPicture from './productPicture'
import channelAttr from './channelAttr.vue'
import textDescription from './textDescription'
import seriesList from './seriesList'
import sinkingAttribute from './sinkingAttribute.vue'
import { transTemplateData, transSavaData } from '@/utils/processingData.js'

export default {
  name: 'JDChannel',
  components: {
    infoItem,
    productPicture,
    channelAttr,
    textDescription,
    seriesList,
    sinkingAttribute
  },
  props: {
    spuData: {
      type: Object,
      required: true
    },
    channelInfo: {
      type: [Object, null],
      default: () => {
        return {}
      }
    },
    isDisabled: {
      type: Boolean,
      default: true
    },
    isEditorDescription: {
      type: Boolean,
      default: false
    },
    increased: {
      type: Boolean,
      default: true
    },
    getSinkingAttributeFun: {
      type: Function,
      default() {
        return () => {}
      }
    },
    savaSinkingAttributeFun: {
      type: Function,
      default() {
        return () => {}
      }
    }
  },
  data() {
    return {
      headerList: [
        {
          label: `商品信息`,
          id: '1'
        },
        {
          label: '商品图片',
          id: '2'
        },
        {
          label: '商品详情页',
          id: '3'
        },
        {
          label: '商品系列',
          id: '4'
        }
      ],
      spuResourceList: {
        mainGraph: [],
        transparencyDrawing: []
      },
      mainSaleAttrName: null,
      mainSaleAttrValueList: [],
      isChange: false,
      current: 0,
      dialogVisible: false,
      sinkingAttributeInfo: {
        spuChannelCategoryAttrList: []
      },
      loading: false
    }
  },
  computed: {
    theadList: {
      get() {
        const arrList = []
        const { mainAttrName, secondaryAttrName } = this.spuData
        if (mainAttrName) {
          arrList.push({
            name: `* ${mainAttrName}`,
            label: `${mainAttrName}`,
            minWidth: '100',
            value: 'mainAttrValueAlias'
          })
        }
        if (secondaryAttrName) {
          arrList.push({
            name: `${secondaryAttrName}`,
            label: `${secondaryAttrName}`,
            minWidth: '100',
            value: 'secondAttrValueAlias'
          })
        }
        return [
          ...arrList,
          {
            name: 'UPC(不含检验码)',
            value: 'upcWoCd',
            minWidth: '100'
          },
          {
            name: '京东价',
            value: 'premiumPrice',
            minWidth: '100'
          },
          {
            name: 'SKU属性',
            minWidth: '100',
            btnList: [
              {
                text: '修改SKU属性',
                on: 'handleSinkingAttribute'
              }
            ]
          }
        ]
      },
      deep: true
    },
    photoDisable() {
      if (this.isEditorDescription) return !this.isEditorDescription
      else return this.isDisabled
    }
  },
  methods: {
    scrollFunc() {
      const domList = document.querySelectorAll("[id^='anchor']")
      const contentList = [...domList].map((_) => _.offsetTop + _.offsetHeight)
      const scrollHeight = this.$refs.contentRight.scrollHeight
      const height = this.$refs.contentRight.clientHeight
      const top = this.$refs.contentRight.scrollTop
      if (top + height === scrollHeight) {
        this.current = domList.length - 1
      } else {
        this.current = contentList.findIndex((_) => _ > top) || 0
      }
    },
    checkFormData() {
      const refs = this.$refs
      const refsKey = Object.keys(this.$refs)
      const check = []
      refsKey.forEach((_) => {
        if (refs[_].submitForm) check.push(refs[_].submitForm())
      })
      const flag = check.every((_) => _)
      console.log(check, flag)
      return flag
    },
    saveSpuChannelInfo() {
      this.checkFormData()
      this.$emit('saveSpuChannelInfo')
    },
    async handleSinkingAttribute({ row }) {
      console.log(this.$route.query)
      const data = {
        channelId: this.channelInfo.channelId
      }
      if (this.spuData.spuCode) data.spuCode = this.spuData.spuCode
      console.log('this.spuData', this.spuData)
      if (row.upcNbr) {
        data.upc = row.upcNbr
        this.sinkingAttributeInfo.upc = row.upcNbr
        if (this.$route.query.spuCode && !data.spuCode) data.spuCode = this.$route.query.spuCode
      }
      if (this.spuData.spuId) {
        data.spuId = this.spuData.spuId
        this.sinkingAttributeInfo.spuId = this.spuData.spuId
      }
      if (this.spuData.chgSpuId) {
        data.chgSpuId = this.spuData.chgSpuId
        this.sinkingAttributeInfo.chgSpuId = this.spuData.chgSpuId
      }
      console.log('data***', data)
      const { result } = await this.getSinkingAttributeFun(data)
      // console.log('*******************', result)
      if (!Array.isArray(result) || !result.length) {
        this.$message({
          type: 'warning',
          message: '未查询到商品的sku属性'
        })
        return
      }
      transTemplateData(result, false, true, true)
      // console.log('*******************', result)
      this.sinkingAttributeInfo.spuChannelCategoryAttrList = result
      this.dialogVisible = true
    },
    async submitSinkingAttribute() {
      try {
        this.loading = true
        const data = JSON.parse(JSON.stringify(this.sinkingAttributeInfo))
        data.channelId = this.channelInfo.channelId
        transSavaData(data.spuChannelCategoryAttrList, false)
        // console.log('***修改', data)
        const { code } = await this.savaSinkingAttributeFun(data)
        if (code !== '0') return
        this.dialogVisible = false
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.JD-channel {
  header {
    margin: 0 12px;
    display: flex;
    justify-content: flex-end;
  }
  .channel-content {
    height: calc(100vh - 148px);
    display: flex;
    .content-left {
      z-index: 2;
      padding: 0 10px;
      display: flex;
      flex-direction: column;
      /deep/ .el-button-text {
        margin: 0;
        color: unset;
      }
      .btn-active {
        color: #0071ce;
      }
    }
    .content-right {
      position: relative;
      &::-webkit-scrollbar {
        width: 8px;
      }
      margin-left: 16px;
      overflow-y: auto;
      flex: 1;
    }
  }
}
strong {
  font-weight: 400;
  writing-mode: vertical-rl;
}
</style>
